package queue;

import java.util.ArrayDeque;
import java.util.Queue;

//基于单链表来模拟实现队列
public class MyQueue {
    static class Node{
        public String val;
        public Node next;
        public Node(String val){
            this.val = val;
        }
    }
    //基于链表的实现,可以入队是头插,出队是尾删,当然,也完全可以反过来,为了好理解,将链表的头作为队列的头
    //将链表的尾作为队列的尾

    private Node head = null;

    private Node tail = null;
    public void offer(String val){
        Node newNode = new Node(val);
        //链表为空
        if(head == null){
            head = newNode;
            tail = newNode;
            return;
        }
        tail.next = newNode;
        tail = newNode;
    }

    public String poll(){
        //头删
        if(head == null){
            return null;
        }
        String val = head.val;
        head = head.next;
        if(head == null){
            tail = null;
        }
        return val;
    }

    public String peek(){
        if(head == null){
            return null;
        }
        return head.val;
    }

    public int size(){
        int size = 0;
        for(Node cur = head;cur != null;cur = cur.next){
            size++;
        }
        return size;
    }




    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        queue.offer("1");
        queue.offer("2");
        queue.offer("3");
        queue.offer("4");
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.peek());
        System.out.println(queue.size());

        //也可以基于数组来实现队列
        Queue<Integer> queue2 = new ArrayDeque<>();
        queue2.offer(1);
        System.out.println("----------------------------");
        System.out.println(queue2.poll());
    }

}

